<template>
    <div class="register">
      <div class="title">注册页</div>
      <van-form  @submit="register">
  <!-- 通过 pattern 进行正则校验 -->
  <van-field
    v-model="formData.phone"
    placeholder="输入手机号"
    :rules="[{require:true, pattern:/^1[3-9]\d{9}$/, message: '手机号格式错误' }]"
  />
  <van-field
    v-model="formData.pass"
    placeholder="输入密码"
    :rules="[{ require:true,message: '密码为空或密码格式错误' }]"
  />
  <van-field
    v-model="formData.checkpass"
    placeholder="确认密码"
    :rules="[{require:true,message: '两次密码不一致' }]"
  />
  <div style="margin: 16px;">
    <van-button round block type="info" native-type="submit">注册</van-button>
  </div>
</van-form>
</div>
  </template>
  
  <script>
  import { Register } from '../utils/service'
  import{Toast} from 'vant'
  export default {
    data(){
      return {
        formData:{
          phone:'',
          pass:'',
          checkpass:''
        }
      }
    },
    methods:{
        register(){
        // if( /^1[3-9]\d{9}$/.test( this.formData.phone ) == false ){
        //   alert('请输入合法的手机号');
        // }else 
        if( !this.formData.pass || !this.formData.checkpass ){
          Toast.fail("密码格式错误")

        }else if( this.formData.pass !== this.formData.checkpass){
          Toast.fail('密码和确认密码不一致');
        }else{ //验证通过 
  
          //深拷贝formData
          var newFormData = JSON.parse( JSON.stringify( this.formData ) );
          //删除对象的checkpass属性
          delete newFormData.checkpass;
  
          //发起注册请求
          Register( newFormData ).then((res)=>{
            if( res.data.code == 200 ){ //注册成功
                Toast.success('注册成功!')
              //跳转到登录页
              this.$router.push('/login');
            }else{
                Toast.fail(res.data.msg)
            }
          })
  
        }
      }
    }
  }
  </script>
  
  <style lang='scss' scoped> 
  .register{
    margin: 50px 20px;
  }
  .register .title{
    font-weight: bold;
    text-align: center;
    line-height: 40px;
  }
  .register .block{
    margin: 20px 0;
  }
  .register .block input{
    height: 40px;
    border: 1px solid #ccc;
    border-radius: 20px;
    padding-left: 20px;
    box-sizing: border-box;
    outline: none;
    width: 100%;
  }
  </style>